import { ipcMain } from "electron";
import fetch from "node-fetch";
import type { DownloadParam, HttpResult } from "@common/http-service-types";
import { DownloadTask } from "@electron/main/task/download-task";
import { getWindow } from "@electron/main/ipc-service/window-holder";

ipcMain.handle("http:get", async (_, url: string, type: "json" | "text" = "json") => {
  return await fetch(url)
    .then(async res => <HttpResult>{ data: await (type === "json" ? res.json() : res.text()) })
    .catch(reason => <HttpResult>{ error: reason?.toString() ?? reason?.toString() });
});

ipcMain.handle("http:post", async (_, url: string, body: any) => {
  return await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  })
    .then(async res => <HttpResult>{ data: await res.json() })
    .catch(reason => <HttpResult>{ error: reason?.toString() ?? reason?.toString() });
});

// 下载文件

const tasks = new Map<string, any>();

ipcMain.on("http:download", (event, param: DownloadParam) => {
  const task = new DownloadTask(param.id, param.url, param.savePath, getWindow(event.sender.id));
  tasks.set(task.id, task);
  task.on("error", () => tasks.delete(task.id));
  task.on("complete", () => tasks.delete(task.id));
  task.start();
});

ipcMain.on("http:download:stop", (event, id: string) => {
  tasks.get(id)?.cancel();
  tasks.delete(id);
});

// 下载文件 END
